﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Utils.Configuration;
using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.EC2.Util;
using Sustainalytics.AwsS3.Client;
using Sustainalytics.ScreeningTool.BL;
using Sustainalytics.DataLayer.Shared;

namespace Sustainalytics.PregenerateScreeningReports
{
    public  class AWSHelper
    {

/*
AWS Network Settings, Each EC2 instance will use the following settings:
  
Live/Staging Environment
Security Group Id: sg-cfdb4caa
VPC Id: vpc-12e22977
Subnet Id: subnet-d253928b
Availability zone: eu-west-1b
AMI: to be defined before release. Naming policy: Screening-ReleaseVersion-Date. Ex. Screening-4-01012016.ami

Testing Environment
Security Group Id: sg-d92b91bc
VPC Id: vpc-d6b042b3
Subnet Id: subnet-2f0a1269
Availability zone: eu-west-1b
AMI: to be defined before release. 
         
Naming policy: Screening-ReleaseVersion-Test-Date. Ex. Screening-4-Test-01012016.ami          
*/

        //Microsoft Windows Server 2012 R2 Base - ami-7943ec0a


        static public string  ReadMyInstanceId()
        {
            return EC2Metadata.InstanceId;
        }


        static public IEnumerable<string> StartAWSInstances(IEnumerable<string> instances, Action<string> log = null)
        {
            if (instances == null || !instances.Any())
                throw new ArgumentException("intances");
            
            var accesKeyId = SettingsHelper.Read<string>("accesKeyId", "AKIAJKGZZMOFAVOVLHJA");
            var secretKey = SettingsHelper.Read<string>("awsSecretKey", "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");
            var regionName = SettingsHelper.Read<string>("AWSRegion", RegionEndpoint.EUWest1.SystemName);
            var region = RegionEndpoint.GetBySystemName(regionName);

            return StartAWSInstances(instances, accesKeyId, secretKey, region, log);
        }



        static public void CleanS3Storage(string screeningDWcnx, string clientPlatformCnx) 
        {             
            var repoPregenerated = new RepositoryCollection<PregeneratedReport>(screeningDWcnx);
            var s3Client = new S3Client(new S3ClientSettings()
            {
                AccessKey = SettingsHelper.Read("accesKeyId", "AKIAJKGZZMOFAVOVLHJA"),
                SecretAccessKey = SettingsHelper.Read("awsSecretKey", "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"),
                ServiceEndPoint = SettingsHelper.Read("s3ServiceEndPoint", "https://s3-eu-west-1.amazonaws.com/")
            });

            var lastLetter = screeningDWcnx.Contains("ScreeningDW_A")?"_A":screeningDWcnx.Contains("ScreeningDW_B")?"_B":"";                
            var s3Folder = SettingsHelper.Read("s3FolderPregen", "PregeneratedReports") + lastLetter;
            var repoFilter = new RepositoryCollection<Entities.Filter>(clientPlatformCnx);
            var mgr = new PregeneratedReportManager(s3Client, repoPregenerated, repoFilter, s3Folder);
            mgr.CleanupS3();

        }

        private static IEnumerable<string> StartAWSInstances(IEnumerable<string> instances, string accesKeyId, string secretKey, RegionEndpoint region, Action<string> log)
        {
            using (var client = new AmazonEC2Client(accesKeyId, secretKey, region)) 
            {
                var req = new StartInstancesRequest(instances.ToList());
                var response = client.StartInstances(req);

                if (log != null)
                {
                    var text = string.Join(", ", response.StartingInstances.Select(x => string.Format("({0}:{1})", x.InstanceId, x.CurrentState.Name)));
                    log("Worker machines: " + text);
                }
                return response.StartingInstances.Select(x => x.InstanceId);
            }
        }
        
    }
}
